/*
 * @Descripttion: 自定义模态弹框组件，组件内执行完取消和确定操作后回调给外部
 * @Author: daxiong
 * @Date: 2020-08-20 17:18:44
 * @LastEditors: daxiong
 * @LastEditTime: 2020-10-15 15:59:26
 * @FilePath: e:\rn-dev\react-native-myapp\src\component\ShowModal\index.js
 */
import React, { Component } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Modal,
  Dimensions,
} from "react-native";
import {
  css,
  border,
  borderB,
  borderT,
  borderL,
  borderR,
  padding,
  paddingLR,
  paddingTB,
  paddingT,
  paddingR,
  paddingB,
  paddingL,
  marginLR,
  marginTB,
  marginT,
  marginR,
  marginB,
  marginL,
  fontSize,
  bdRadius,
} from "../../utils/BaseStyle";
import { scaleSize } from "../../utils/ScreenUtils";
const { width } = Dimensions.get("window");

/**
 * 使用方法：
 * 1.外部引用组件路径，在render内写上组件
 * 2.调用组件内的show方法，传相关参数即可
 */
// 步骤一：
// import ShowModal from '../../../../components/ShowModal';
// 步骤二：
// <ShowModal ref={e => {this.ShowModal = e}} />
// 步骤三：
// this.ShowModal.show({
//     title: '取消预约',
//     content: '顾客的预约金将原路退款，确定取消预约吗？',
//     success: res => {
//         console.log('收到子组件的回调', res);
//         //点击了确定
//         if (res.confirm) {}
//         //点击了取消
//         if (res.cancel) {}
//     },
// });

export default class ShowModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      title: "", //弹框标题
      content: "提示内容", //默认内容
      btns: ["取消", "确定"], //默认按钮
      success: null,
    };
  }

  static defaultProps = {
    title: "", //弹框标题
    content: "提示内容", //默认内容
    btns: ["取消", "确定"], //默认按钮
  };

  componentDidMount() {}

  /**
   * 模态按钮事件响应，如果外部没有传success，默认自动处理‘取消’和‘确定’操作，即直接关闭模态
   * @param {String} item 按钮名称
   * @param {Number} index 按钮索引
   */
  btnEventHanle(item, index) {
    if (this.state.btns.length === 1) {
      if (this.state.success && typeof this.state.success === "function") {
        this.state.success({ cancel: false, confirm: true });
      }
      this.close();
      return;
    }
    //取消事件
    if (index === 0) {
      if (this.state.success && typeof this.state.success === "function") {
        this.state.success({ cancel: true, confirm: false });
      }
      this.close();
    }
    //确定事件
    if (index === 1) {
      if (this.state.success && typeof this.state.success === "function") {
        this.state.success({ cancel: false, confirm: true });
      }
      this.close();
    }
  }

  close() {
    this.setState({
      modalVisible: false,
    });
  }

  open() {
    this.setState({
      modalVisible: true,
    });
  }

  /**
   * 供外部调用，收到外部传进来的模态相关state值
   * @param {String} title 模态标题
   * @param {String} content 模态提示内容
   * @param {Function} success 模态回调方法
   * @returns null
   * @memberof ShowModal
   */
  show(res) {
    const _show = () => {
      this.state.title = res.title ? res.title : this.props.title;
      this.state.content = res.content ? res.content : this.props.content;
      this.state.btns =
        res.btns && res.btns.length > 0 ? res.btns : this.props.btns;
      if (res.success && typeof res.success === "function") {
        this.state.success = res.success;
      } else {
        this.state.success = null;
      }
      this.setState({
        title: this.state.title,
        content: this.state.content,
      });
      this.open();
    };
    if (typeof res === "object") {
      if (JSON.stringify(res) === "{}") {
        // console.error('The show method parameter of the showModal component should not be an empty object.');
        _show();
        return;
      }
      if (Array.isArray(res)) {
        console.error(
          "The show method parameter of the showModal component should be an object."
        );
        return;
      }
      _show();
    } else {
      console.error(
        "The show method parameter of the showModal component should be an object."
      );
    }
  }

  render() {
    const { content } = this.state;
    return (
      <Modal
        animationType={"none"}
        transparent={true}
        visible={this.state.modalVisible}
      >
        <View
          style={[
            css.flex1,
            css.flexVH,
            { backgroundColor: "rgba(0,0,0,0.3)" },
          ]}
        >
          <View
            style={[
              css.vh,
              css.flexCol,
              bdRadius(16),
              { width: width - scaleSize(200), backgroundColor: "#ffffff" },
            ]}
          >
            {this.renderTitleView()}
            <View
              style={[
                marginLR(30),
                marginB(18),
                css.flexVH,
                {
                  minHeight: scaleSize(160),
                  MaxHeight: scaleSize(500),
                },
              ]}
            >
              <Text style={[fontSize(30), css.c9]} numberOfLines={8}>
                {content}
              </Text>
            </View>
            {this.renderBtnView()}
          </View>
        </View>
      </Modal>
    );
  }

  //返回标题视图
  renderTitleView() {
    const { title } = this.state;
    if (title) {
      return (
        <View style={[css.flexVH, marginT(30), marginB(10)]}>
          <Text
            style={[css.fb, css.c3, fontSize(34), paddingLR(30)]}
            numberOfLines={1}
          >
            {title}
          </Text>
        </View>
      );
    } else {
      return <View style={[css.flexVH, marginT(30), marginB(10)]} />;
    }
  }

  renderBtnView() {
    let { btns } = this.state;
    if (!btns || btns.length === 0) return;
    return (
      <View
        style={[
          borderT("#F1F1F1", 0.5),
          css.flexRow_sb,
          { height: scaleSize(88) },
        ]}
      >
        {btns.map((item, index) => {
          return this.renderBtnItem(item, index);
        })}
      </View>
    );
  }

  // 返回按钮
  renderBtnItem(item, index) {
    let { btns } = this.state;
    if (!btns || btns.length === 0) return;
    let dynBtnStyle = [],
      dynTextStyle = [];

    if (index === 0) {
      dynBtnStyle = [borderR("#F1F1F1", 0.5)];
      dynTextStyle = { color: "#9A9A9A" };
    }
    if (index === 1) {
      dynBtnStyle = [{}];
      dynTextStyle = [css.c3];
    }
    return (
      <TouchableOpacity
        key={index}
        style={[css.flex1, dynBtnStyle, { width: "100%", height: "100%" }]}
        activeOpacity={0.6}
        onPress={() => this.btnEventHanle(item, index)}
      >
        <View style={[css.flexVH, { width: "100%", height: "100%" }]}>
          <Text style={[fontSize(29), dynTextStyle]}>{item}</Text>
        </View>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({});
